const express = require("express");
const router = express.Router();
const fs = require("fs").promises;
const path = require("path");
const iconv = require("iconv-lite");
const { group } = require("console");

// 获取所有语法条目
router.get("/", async (req, res) => {
  try {
    const grammarDir = path.join(__dirname, "../../resources/grammar");
    const files = await fs.readdir(grammarDir);

    // 过滤出.txt文件并提取标题
    const txtFiles = files.filter((file) => file.endsWith(".txt"));

    const grammarList = [];
    for (const file of txtFiles) {
      try {
        const filePath = path.join(grammarDir, file);
        const contentBuffer = await fs.readFile(filePath);
        const decodedContent = iconv.decode(contentBuffer, "gbk");

        // 从文件内容中提取标题（第一行）
        const lines = decodedContent.split("\n");
        const titleLine = lines[0].trim();
        const title = titleLine || file.replace(".txt", "");
        grammarList.push({
          filename: file,
          title: title,
        });
      } catch (fileError) {
        console.error(`Error reading file ${file}:`, fileError);
      }
    }

    // 按标题排序
    grammarList.sort((a, b) => a.title.localeCompare(b.title));
    const g = sortArray(grammarList);
    g.sort((a, b) => {
      if (a.id === "-") return 1;
      if (b.id === "-") return -1;
      return Number.parseInt(a.id) - Number.parseInt(b.id);
    });
    res.json(g);
  } catch (error) {
    console.error("Error fetching grammar list:", error);
    res
      .status(500)
      .json({ message: "Error fetching grammar list", error: error.message });
  }
});

/**
 * 对语法列表进行排序
 * @param {Array} grammarList 语法列表
 * @returns {Array} 排序后的语法列表
 */
function sortArray(grammarList) {
  // 如果数组为空，则返回空数组
  if (grammarList.length === 0) {
    return [];
  }
  const groups = [];
  for (let i = 0; i < grammarList.length; i++) {
    const title = grammarList[i].title;
    const filename = grammarList[i].filename;
    const firstDot = title.indexOf(".");
    const beforeDotChars = firstDot > -1 ? title.substring(0, firstDot) : "-";
    const groupName = firstDot > -1 ? title.substring(firstDot + 1) : "其他";
    let findGroup = false;
    for (let j = 0; j < groups.length; j++) {
      if (groups[j].id === beforeDotChars) {
        const idx = title.indexOf(" ");
        grammarList[i].sortID = title.substring(firstDot+1, idx);
        groups[j].items.push(grammarList[i]);
        findGroup = true;
        break;
      }
    }
    if (!findGroup) {
      groups.push({
        id: beforeDotChars,
        groupName: groupName,
        filename,
        items: [],
      });
    }
  }
  for(let i = 0; i < groups.length; i++){
    const items = groups[i].items;
    groups[i].items = items.sort((a, b) => {
      return Number.parseInt(a.sortID) - Number.parseInt(b.sortID);
    });
  }
  
  return groups;
}

// 获取特定语法条目的内容
router.get("/:filename", async (req, res) => {
  try {
    const { filename } = req.params;
    const { format = "text" } = req.query; // 支持format参数，可选值: text (默认), markdown

    if (format === "markdown") {
      // 直接读取markdown文件
      const mdFilename = filename.replace(".txt", ".md");
      const mdFilePath = path.join(
        __dirname,
        "../../resources/grammar_md",
        mdFilename
      );

      // 检查markdown文件是否存在
      try {
        await fs.access(mdFilePath);
        const content = await fs.readFile(mdFilePath, "utf-8");

        // 从内容中提取标题（第一行）
        const lines = content.split("\n");
        let title = "";
        if (lines[0].startsWith("# ")) {
          title = lines[0].substring(2).trim();
        } else {
          title = filename.replace(".txt", "");
        }

        // 返回标题和内容（去掉第一行标题行）
        const contentWithoutTitle = lines.slice(1).join("\n").trimStart();

        res.json({
          title: title,
          content: contentWithoutTitle,
        });
      } catch (accessError) {
        return res
          .status(404)
          .json({ message: "Grammar markdown file not found" });
      }
    } else {
      // 确保文件名以.txt结尾
      if (!filename.endsWith(".txt")) {
        return res.status(400).json({ message: "Invalid filename" });
      }

      const filePath = path.join(
        __dirname,
        "../../resources/grammar",
        filename
      );

      // 检查文件是否存在
      try {
        await fs.access(filePath);
      } catch (accessError) {
        return res.status(404).json({ message: "Grammar file not found" });
      }

      // 读取并解码文件内容 (使用GBK编码)
      const contentBuffer = await fs.readFile(filePath);
      const content = iconv.decode(contentBuffer, "gbk");

      // 从内容中提取标题（第一行）
      const lines = content.split("\n");
      const title = lines[0].trim() || filename.replace(".txt", "");

      // 返回标题和内容（去掉第一行标题行）
      let contentWithoutTitle = lines.slice(1).join("\n").trimStart();
      // 将多个空行替换为一个空行
      contentWithoutTitle = contentWithoutTitle.replace(/\n{2,}/g, "\n");

      res.json({
        title: title,
        content: contentWithoutTitle,
      });
    }
  } catch (error) {
    console.error("Error fetching grammar content:", error);
    res.status(500).json({
      message: "Error fetching grammar content",
      error: error.message,
    });
  }
});

module.exports = router;
